<style rel="stylesheet/scss" lang="scss" scoped>
.dashboard-editor-container {
  padding: 18px 22px 22px 22px;
  background-color: rgb(240, 242, 245);

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }
}

.form-operator-button {
  background-color: #fff;
  position: fixed;
  width: 100%;
  left: 0px;
  right: 0;
  bottom: 33px;
  height: 64px;
  line-height: 64px;
  text-align: center;
  box-shadow: 0 -1px 2px 0 rgba(0, 0, 0, 0.05);
  z-index: 999;
}

.hex-form-inf {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  cursor: pointer;
  margin-right: 40px;
  position: relative;
  min-height: 33px;
  margin-left: 60px;
  line-height: 33px;
  color: #347de1;
}

.hex-form-inf-content {
  font-size: 14px;
  font-weight: 500;
  display: none;
}

.hex-form-inf-icon {
  font-size: 20px;
  margin-top: 5px;
  position: absolute;
  right: 0px;
}

.el-page-header__content {
  font-size: 14px;
}

.el-page-header__title {
  font-size: 14px;
}

.hex-form-inf .hex-form-inf-content-show {
  padding: 0 4%;
  background-color: #f7f9fa;
  border: 1px solid #347de1;
  border-radius: 8px;
}

.hex-form-inf-content {
  font-size: 14px;
  font-weight: 500;
  display: none;
}
</style>
<template>
  <div class="dashboard-container">
    <div class="dashboard-editor-container">
      <el-card class="box-card" v-if="crud.optPageShow.listPage">
        <div slot="header" class="clearfix">
          <span class="el-page-header__content">用户列表</span>
        </div>
        <div>
          <!--工具栏-->
          <div class="head-container">
            <crudOperation :permission="permission"/>
          </div>
          <!--表格渲染-->
          <el-table ref="table" :data="crud.data" style="width: 100%;" v-loading="crud.loading"
                    @select="crud.selectChange" @select-all="crud.selectAllChange"
                    @selection-change="crud.selectionChangeHandler" @filter-change="crud.handleFilterChange"
                    :header-cell-style="{ background: 'rgba(52, 125, 225, 0.1)', color: '#404248' }" border stripe>
            <el-table-column type="selection"/>
            <el-table-column v-if="columns.visible('username')" :show-overflow-tooltip="true" prop="username"
                             label="用户名"/>
            <el-table-column v-if="columns.visible('nickName')" :show-overflow-tooltip="true" prop="nickName"
                             label="姓名"/>
            <el-table-column v-if="columns.visible('sex')" prop="sex" label="性别"/>
            <el-table-column v-if="columns.visible('phone')" :show-overflow-tooltip="true" prop="phone" label="电话"/>
            <el-table-column v-if="columns.visible('email')" :show-overflow-tooltip="true" prop="email" label="邮箱"/>
            <el-table-column v-if="columns.visible('createTime')" :show-overflow-tooltip="true" prop="createTime"
                             label="创建日期">
              <template slot-scope="scope">
                <i class="el-icon-time"></i>
                <span style="margin-left: 10px">{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
      <el-card class="box-card" v-if="crud.optPageShow.addPage">
        <div slot="header" class="clearfix">
          <div class="el-page-header">
            <div class="el-page-header__left" @click="crud.goBack">
              <i class="el-icon-back"></i>
              <div class="el-page-header__title">返回</div>
            </div>
            <div class="el-page-header__content"><b>用户信息编辑</b></div>
          </div>
        </div>
        <div class="dataFrom">
          <el-form ref="form" :model="form" :rules="rules" label-position="left" label-width="240px">
            <div>
              <el-row v-if="form.id  == null">
                <el-col :span="12">
                  <el-form-item label="类型" prop="dataType">
                    <el-radio-group v-model="form.dataType" @change="dataTypeChange">
                      <el-radio-button label="1">创建新用户</el-radio-button>
                      <el-radio-button label="2">选择已有用户</el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="9" class="data_from_el-col">
                  <div class="hex-form-inf">
                    <div class="hex-form-inf-content">
                      创建新用户或关联已存在的用户
                    </div>
                    <i class="el-icon-info hex-form-inf-icon" @click="onOperInf($event)" data-status="off"></i>
                  </div>
                </el-col>
              </el-row>
              <el-row v-if="form.dataType == 2 && form.id  == null">
                <el-col :span="12">
                  <el-form-item label="姓名" prop="username">
                    <el-select v-model="form.username" filterable placeholder="请选择" style="width: 100%">
                      <el-option v-for="item in userList" :key="item.username" :label="item.nickName"
                                 :value="item.username">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="9" class="data_from_el-col">
                  <div class="hex-form-inf">
                    <div class="hex-form-inf-content">
                      请选择用户
                    </div>
                    <i class="el-icon-info hex-form-inf-icon" @click="onOperInf($event)" data-status="off"></i>
                  </div>
                </el-col>
              </el-row>
              <el-row v-if="form.dataType == 1">
                <el-col :span="12">
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username" v-bind:disabled="form.id"/>
                  </el-form-item>
                </el-col>
                <el-col :span="9" class="data_from_el-col">
                  <div class="hex-form-inf">
                    <div class="hex-form-inf-content">
                      输入用户用户名
                    </div>
                    <i class="el-icon-info hex-form-inf-icon" @click="onOperInf($event)" data-status="off"></i>
                  </div>
                </el-col>
              </el-row>
              <el-row v-if="form.dataType == 1">
                <el-col :span="12">
                  <el-form-item label="电话" prop="phone">
                    <el-input v-model.number="form.phone"/>
                  </el-form-item>
                </el-col>
                <el-col :span="9" class="data_from_el-col">
                  <div class="hex-form-inf">
                    <div class="hex-form-inf-content">
                      输入用户的电话号码
                    </div>
                    <i class="el-icon-info hex-form-inf-icon" @click="onOperInf($event)" data-status="off"></i>
                  </div>
                </el-col>
              </el-row>
              <el-row v-if="form.dataType == 1">
                <el-col :span="12">
                  <el-form-item label="姓名" prop="nickName">
                    <el-input v-model="form.nickName"/>
                  </el-form-item>
                </el-col>
                <el-col :span="9" class="data_from_el-col">
                  <div class="hex-form-inf">
                    <div class="hex-form-inf-content">
                      输入用户姓名（英文或中文名称）
                    </div>
                    <i class="el-icon-info hex-form-inf-icon" @click="onOperInf($event)" data-status="off"></i>
                  </div>
                </el-col>
              </el-row>
              <el-row v-if="form.dataType == 1">
                <el-col :span="12">
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email"/>
                  </el-form-item>
                </el-col>
                <el-col :span="9" class="data_from_el-col">
                  <div class="hex-form-inf">
                    <div class="hex-form-inf-content">
                      输入用户邮箱
                    </div>
                    <i class="el-icon-info hex-form-inf-icon" @click="onOperInf($event)" data-status="off"></i>
                  </div>
                </el-col>
              </el-row>
              <el-row v-if="form.dataType == 1">
                <el-col :span="12">
                  <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="form.sex" style="width: 178px">
                      <el-radio label="男">男</el-radio>
                      <el-radio label="女">女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="9" class="data_from_el-col">
                  <div class="hex-form-inf">
                    <div class="hex-form-inf-content">
                      选择用户的性别
                    </div>
                    <i class="el-icon-info hex-form-inf-icon" @click="onOperInf($event)" data-status="off"></i>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item style="margin-bottom: 0;" label="角色" prop="roles">
                    <el-select v-model="form.roles" style="width: 100%" filterable multiple placeholder="请选择"
                               @remove-tag="deleteTag" @change="changeRole">
                      <el-option v-for="item in roles" :key="item.name" :disabled="level !== 1 && item.level <= level"
                                 :label="item.name" :value="item.id"/>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="9" class="data_from_el-col">
                  <div class="hex-form-inf">
                    <div class="hex-form-inf-content">
                      请选择用户的角色
                    </div>
                    <i class="el-icon-info hex-form-inf-icon" @click="onOperInf($event)" data-status="off"></i>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-form>
        </div>
        <div class="form-operator-button">
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">
            保存
          </el-button>
          <el-button @click="crud.goBack">返回</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import crudUser from '@/api/system/user'
import appUser from '@/api/system/appUser'
import {isvalidPhone, validateUserName} from '@/utils/validate'
import {getAll, getLevel} from '@/api/system/role'
import CRUD, {presenter, header, form, crud} from '@crud/crud'
import crudOperation from '@crud/extend/appUser/CRUD.appUserOperation'
import Treeselect from '@riophae/vue-treeselect'
import {mapGetters} from 'vuex'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

const queryList = [{'cloumValue': 'username', 'cloumName': '用户名'}
  , {'cloumValue': 'nickName', 'cloumName': '姓名'}
  , {'cloumValue': 'email', 'cloumName': '邮箱'}
  , {'cloumValue': 'phone', 'cloumName': '电话'}
]
let userRoles = []
// crud交由presenter持有
const defaultCrud = CRUD({
  title: '用户',
  url: 'api/appUser/selectAppUser',
  queryList: queryList,
  crudMethod: {...appUser}
})
const defaultForm = {
  id: null,
  dataType: '1',
  username: null,
  nickName: null,
  sex: '男',
  email: null,
  enabled: 'false',
  roles: [],
  dept: {id: 1},
  phone: null
}
export default {
  name: 'appUser',
  components: {Treeselect, crudOperation},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  // 数据字典
  dicts: ['user_status'],
  data() {
    // 自定义验证
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    const validUserName = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!validateUserName(value)) {
        callback(new Error('用户名只能包含字母或数字'))
      } else {
        if (this.crud.form.dataType === '1') {
          appUser.findUserByUserName(value).then(res => {
            if (res != null && res.username == this.form.username && res.id != this.crud.form.id) {
              callback(new Error("该用户已存在，请选择添加"));
            } else {
              callback();
            }
          })
        } else {
          callback();
        }
      }
    }
    return {
      height: document.documentElement.clientHeight - 180 + 'px;',
      level: 3, roles: [],
      defaultProps: {children: 'children', label: 'name'},
      permission: {
        add: ['appUser:add'],
        edit: ['appUser:edit'],
        del: ['appUser:del']
      },
      enabledTypeOptions: [
        {key: 'true', display_name: '激活'},
        {key: 'false', display_name: '锁定'}
      ],
      rules: {
        username: [
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'},
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {required: true, trigger: 'change', validator: validUserName}
        ],
        nickName: [
          {required: true, message: '请输入用户姓名', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱地址', trigger: 'blur'},
          {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
        ],
        phone: [
          {required: true, trigger: 'blur', validator: validPhone}
        ],
        roles: [
          {required: true, trigger: 'blur', message: '请选择角色',}
        ],
        dataType: [
          {required: true, trigger: 'blur', message: '请选择类型',}
        ],
        sex: [
          {required: true, trigger: 'blur', message: '请选择性别',}
        ]
      },
      userList: [],
      validNameStatus: false
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    this.crud.optPageShow.addPage = false;
    this.crud.optPageShow.listPage = true;
  },
  mounted: function () {
    const that = this
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px;'
    }
  },
  methods: {
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.getRoles();
      this.getRoleLevel();
      this.getUserList();
      form.enabled = form.enabled.toString()
    },
    // 打开编辑弹窗前做的操作
    [CRUD.HOOK.afterToEdit](crud, form) {
      appUser.getAppUserRole(form.username).then(res => {
        form.roles = res;
        res.forEach(data => {
          let role = {id: data};
          userRoles.push(role)
        })
      })
    },
    // 删除前
    [CRUD.HOOK.beforeDelete](crud, data) {
      data.forEach(item => {
        item.id = item.username;
      })
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (userRoles.length === 0) {
        this.$message({
          message: '角色不能为空',
          type: 'warning'
        })
        return false
      }
      crud.form.roles = userRoles
      crud.form.createTime = null
      return true
    },
    getUserList() {
      appUser.selectAllUser().then(res => {
        this.userList = res;
      })
    },
    jxOrder(index, row) {
      crudUser.resetPass({username: row.username}).then(res => {
        this.$notify({
          title: '重置密码成功',
          type: 'success',
          duration: 2500
        })
      })
    },
    changeRole(value) {
      userRoles = []
      value.forEach(function (data, index) {
        const role = {id: data}
        userRoles.push(role)
      })
    },
    [CRUD.HOOK.afterAddError](crud) {
      this.afterErrorMethod(crud)
    },
    [CRUD.HOOK.afterEditError](crud) {
      this.afterErrorMethod(crud)
    },
    afterErrorMethod(crud) {
      // 恢复select
      const initRoles = []
      userRoles.forEach(function (role, index) {
        initRoles.push(role.id)
      })
      crud.form.roles = initRoles
    },
    deleteTag(value) {
      userRoles.forEach(function (data, index) {
        if (data.id === value) {
          userRoles.splice(index, value)
        }
      })
    },
    // 获取弹窗内角色数据
    getRoles() {
      getAll().then(res => {
        this.roles = res
      }).catch(() => {
      })
    },
    // 获取权限级别
    getRoleLevel() {
      getLevel().then(res => {
        this.level = res.level
      }).catch(() => {
      })
    },
    checkboxT(row, rowIndex) {
      return row.id !== this.user.id
    },
    onOperInf: function (e) {
      let status = e.target.getAttribute('data-status');
      let previousNode = e.target.previousElementSibling;
      if ("off" == status) {
        previousNode.setAttribute('class', 'hex-form-inf-content-show');
        e.target.setAttribute('data-status', 'on');
      } else {
        previousNode.setAttribute('class', 'hex-form-inf-content');
        e.target.setAttribute('data-status', 'off');
      }
    },
    dataTypeChange(val) {
      this.crud.form.username = null;
      this.crud.form.roles = null;
    }
  }
}
</script>

<style scoped>
</style>
